<template>
    <div class="view">
        <div class="home-radar" v-if="radarShow">
            <radar>
                <div class="face-fade-wrap">
                    <div class="face-fade-item" v-for="(face,index) in faceList" :key="index"
                         :style="'background-image:url('+face.url+');top:'+face.y+'px;left:'+face.x+'px;animation-delay:'+face.delay+'ms'">
                    </div>
                </div>
            </radar>
            <span class="home-radar-text">正在为您搜索周围的异性朋友...</span>
        </div>
        <div class="app-download" v-if="!radarShow && !device.status && setting.download" @click="toDownload">
            <img src="@/assets/images/logo-banner.png">
        </div>
        <div class="encounter-card-wrap" :class="{'encounter-card-wrap-no-app':!device.status && setting.download}">
            <div class="photo-masker" v-if="encounterList.length === 0" :class="{'encounter-card-item-no-app':!device.status && setting.download,'photo-masker-men':user.gender==2}"
                 :style="'z-index:'+(encounterList.length+20)">
                <div class="photo-masker-icon animated infinite flash">?</div>
                <div class="photo-masker-text">神秘的邂逅对象正在赶来</div>
                <div class="photo-masker-text">不妨期待一下</div>
            </div>
            <template v-if="encounterList.length > 0">
                <div class="encounter-card-item" :class="{'encounter-card-item-no-app':!device.status && setting.download}" v-on:click="toLookInfo(currentIsomerism.user_id)"
                     v-finger:press-move="pressMove"
                     :style="'z-index:'+encounterList.length+';transform: '+translateString"
                     v-finger:swipe="touchEnd" v-finger:touch-start="touchStart">
                    <div class="encounter-card-image" :class="{'encounter-card-image-no-app':!device.status && setting.download}"
                         :style="'background-image: url('+currentIsomerism.avatar.file_path+'?imageView2/0/h/'+(clientWidth-20)+'/interlace/1)'"></div>
                    <div class="encounter-card-intro">
                        <div class="encounter-card-desc">
                            <div class="encounter-card-name">{{currentIsomerism.nickName}}
                                <i v-if="currentIsomerism.authentication>0" class="encounter-card-sign">已实名</i>
                                <i class="encounter-card-sign" v-if="currentIsomerism.user_rank>1">{{currentIsomerism.rank_name}}</i>
                            </div>
                            <div class="encounter-card-base">
                                <span v-if="currentIsomerism.age>0"> {{currentIsomerism.age}}岁</span>
                                <template v-if="matchJson('EDUCATION',currentIsomerism.user_info.EDUCATION) !== ''">
                                    <i></i>
                                    <span>{{matchJson('EDUCATION',currentIsomerism.user_info.EDUCATION)}}</span>
                                </template>
                                <template v-if="matchJson('HEIGHT',currentIsomerism.user_info.HEIGHT) !== ''">
                                    <i></i>
                                    <span>{{matchJson('HEIGHT',currentIsomerism.user_info.HEIGHT)}}</span>
                                </template>
                                <template v-if="matchJson('INCOME',currentIsomerism.user_info.INCOME) !== ''">
                                    <i></i>
                                    <span>{{matchJson('INCOME',currentIsomerism.user_info.INCOME)}}</span>
                                </template>
                            </div>
                        </div>
                        <div class="encounter-card-matching">
                            <div class="encounter-card-number">{{currentIsomerism.matchingDegree}}</div>
                            <div class="encounter-card-text">匹配度</div>
                        </div>
                    </div>
                </div>
                <div v-if="index > 0" v-for="(item,index) in encounterList" :class="{'encounter-card-item-no-app':!device.status && setting.download}" class="encounter-card-item"
                     :style="'z-index:'+(encounterList.length - index)+';'">
                    <div class="encounter-card-image" :class="{'encounter-card-image-no-app':!device.status && setting.download}" v-if="index<4"
                         :style="'background-image: url('+item.avatar.file_path+'?imageView2/0/h/'+(clientWidth-20)+'/interlace/1)'"></div>
                    <div class="encounter-card-image" :class="{'encounter-card-image-no-app':!device.status && setting.download}" v-else :style="'background-image: url('+item.avatar.file_path+'?imageView2/0/h/60/q/50)'"></div>

                    <div class="encounter-card-intro">
                        <div class="encounter-card-desc">
                            <div class="encounter-card-name">{{item.nickName}}
                                <i v-if="item.authentication>0" class="encounter-card-sign">已实名</i>
                                <i class="encounter-card-sign" v-if="item.user_rank>1">{{item.rank_name}}</i>
                            </div>
                            <div class="encounter-card-base">
                                <span v-if="item.age>0"> {{item.age}}岁</span>
                                <template v-if="matchJson('EDUCATION',item.user_info.EDUCATION) !== ''">
                                    <i></i>
                                    <span>{{matchJson('EDUCATION',item.user_info.EDUCATION)}}</span>
                                </template>
                                <template v-if="matchJson('HEIGHT',item.user_info.HEIGHT) !== ''">
                                    <i></i>
                                    <span>{{matchJson('HEIGHT',item.user_info.HEIGHT)}}厘米</span>
                                </template>
                                <template v-if="matchJson('INCOME',item.user_info.INCOME) !== ''">
                                    <i></i>
                                    <span>{{matchJson('INCOME',item.user_info.INCOME)}}</span>
                                </template>
                            </div>
                        </div>
                        <div class="encounter-card-matching">
                            <div class="encounter-card-number">{{item.matchingDegree}}</div>
                            <div class="encounter-card-text">匹配度</div>
                        </div>
                    </div>
                </div>
            </template>
        </div>
        <div class="like-number" :class="{'like-number-no-app':!device.status && setting.download}" :style="{'z-index':encounterList.length+30}">
            <i class="iconfont icon-icon4 heartBeat animated infinite"></i>
            <span class="count">{{loveCount}}</span>
        </div>
        <div class="game-tip" :style="{'z-index':encounterList.length+32}" v-if="tipsShow && !radarShow">
            <div class="game-tip-first">
                <div class="game-tip-first-item">
                    <i class="iconfont icon-bhjleftslide"></i>
                    <span class="tip-text">左滑不喜欢</span>
                </div>
                <div class="game-tip-first-item">
                    <i class="iconfont icon-bhjrigthslide"></i>
                    <span class="tip-text">右滑喜欢</span>
                </div>
            </div>
            <div class="game-tip-second">
                <i class="iconfont icon-dianji01"></i>
                <span class="tip-text">点击查看介绍</span>
            </div>
            <div class="game-tip-close" @click="iKnow">知道了</div>
        </div>
    </div>
</template>

<script lang="ts">
    import {Component, Vue} from "vue-property-decorator";
    import Scene from "@/render/Scene";
    import Http from "@/service/Http";

    import {Getter, Action, State, Mutation} from "vuex-class";
    import {InterfaceUser} from "@/interface/InterfaceUser";
    import Radar from "@/components/Radar.vue";

    import CommonUnit from "@/unit/CommonUnit";
    import {updateDataCache} from "@/store/dispatches";

    @Component({
        components: {
            Radar
        }
    })
    export default class Home extends Scene {
        private clientWidth: number = document.body.clientWidth;
        private clientHeight: number = document.body.clientHeight;

        private moveDistance: any = {x: 0, y: 0};
        private encounterList: any[] = [];
        private swipeTimer: number = 0;
        private canSwipe: boolean = true;
        private touchStartTimeStamp: number = 0;
        private touchEndTimeStamp: number = 0;
        private friendId: number = 4;
        private radarShow: boolean = true;
        private parameterItem: any = {};
        private parameterKey: string[] = ["HEIGHT", "EDUCATION", "INCOME"];
        private heightList: any[] = [];
        private animationTime: number = 0;
        private loveCount: number = 0;
        private tipsShow: boolean = false;

        @State("UserStore")
        public user!: InterfaceUser;

        @State("DeviceStore")
        private device: any;

        @State("SettingStore")
        private setting: any;

        @State("DataCacheStore")
        public dataCache!: any;

        private activated() {
            this.$nextTick(() => {
                if (this.encounterList.length === 0) {
                    this.initData();
                }
            });
        }

        // private created():void{
        //     console.log(this.user.gender,this.user.gender === 0);
        //     if (this.user.gender === 0) {
        //         this.switchTab({name: "mineAvatarAndSex"});
        //     }
        // }

        private get currentIsomerism(): any {
            return this.encounterList[0] || {};
        }

        private get circle(): any {
            const circle: any = {};
            circle.radius = document.body.clientWidth / 2;
            circle.validRadius = (document.body.clientWidth / 2) - (document.body.clientWidth / 3.5);
            circle.targetRadius = document.body.clientWidth / 3.5;
            return circle;
        }

        private get translateString(): string {
            return `translate(${this.moveDistance.x}px,${this.moveDistance.y}px)`;
        }

        private get coverPhoto(): any {
            return this.encounterList[0];
        }

        private get resetDistance(): number {
            return Math.sqrt(Math.pow(document.body.clientWidth / 10, 2) + Math.pow(document.body.clientHeight / 10, 2));
        }

        private async initData() {
            this.radarShow = true;
            this.getLoveCount();
            for (let i in this.parameterKey) {
                this.getParameterItem(this.parameterKey[i]);
            }
            await this.getIsomerism();
            setTimeout(() => {
                this.radarShow = false;
            }, 100000);
        }

        // private mounted() {
        //     this.initData();
        // }


        private pressMove(evt: any): void {
            this.moveDistance.x = this.moveDistance.x + evt.deltaX;
            this.moveDistance.y = this.moveDistance.y + evt.deltaY;
        }

        private get faceList(): any[] {
            const faceList = [];
            this.animationTime = 0;
            for (let i in this.encounterList) {
                const coordinate: any = this.calculateCoordinate();
                const delay: number = Number(i) * (Math.random() * 200 + 800);
                this.animationTime = this.animationTime + delay;
                faceList.push({
                    url: this.encounterList[i].avatar.file_path + "?imageView2/0/h/60/q/50",
                    x: coordinate.x,
                    y: coordinate.y,
                    delay: delay
                });
            }
            const time = this.encounterList.length * 1000;
            setTimeout(() => {
                this.radarShow = false;
            }, 10000);
            return faceList;
        }

        private calculateCoordinate(): any {
            let y: number = CommonUnit.getRandomNum(-this.circle.validRadius, this.circle.validRadius);
            const symbol = Math.random() < .5 ? -1 : 1;
            let x: number = symbol * Math.sqrt(Math.pow(this.circle.validRadius, 2) - Math.pow(y, 2));
            y = this.circle.radius - y;
            x = this.circle.radius - x;
            return {x, y};
        }


        private touchStart(): void {
            this.touchStartTimeStamp = new Date().getTime();
        }

        private touchEnd(): void {
            const modeDistanceTotal = Math.sqrt(Math.pow(this.moveDistance.x, 2) + Math.pow(this.moveDistance.y, 2));
            if (modeDistanceTotal < this.resetDistance) {
                setTimeout(() => {
                    this.moveDistance = {x: 0, y: 0};
                }, 100);
            } else {
                this.touchEndTimeStamp = new Date().getTime();
                if (this.moveDistance.x < 0) {
                    this.leftHate();
                } else {
                    this.rightLike();
                }
            }


        }

        private iKnow(): void {
            this.tipsShow = false;
            updateDataCache({gameTip: false});
        }

        private cutCardEffect(type: number) {
            const url = type === 1 ? this.api.preferById : this.api.dislikeById;
            Http.post(url, {id: this.currentIsomerism.user_id}, {token: this.user.token}).finally(() => {
                this.getLoveCount();
                if (this.encounterList.length < 10) {
                    this.getIsomerism();
                }
            });
            let timeDiff = (this.touchEndTimeStamp - this.touchStartTimeStamp) / 20;
            timeDiff = timeDiff < 10 ? timeDiff : 10;
            this.swipeTimer = setInterval(() => {
                const stepX = this.moveDistance.x / timeDiff;
                const stepY = this.moveDistance.y / timeDiff;
                this.moveDistance = {x: this.moveDistance.x + stepX, y: this.moveDistance.y + stepY};
                if (this.moveDistance.x > this.clientWidth || this.moveDistance.x < -this.clientWidth) {
                    clearInterval(this.swipeTimer);
                    this.encounterList.splice(0, 1);
                    this.moveDistance = {x: 0, y: 0};
                }
            }, 10);

        }

        private leftHate(): void {
            this.cutCardEffect(0);

        }

        private rightLike(): void {
            // alert("喜欢");
            this.loveCount = this.loveCount + 1;
            this.cutCardEffect(1);
        }

        private toLookInfo(friendId: number): void {
            // 跳转到好友详情
            this.navigateTo({
                name: "friendInfo",
                query: {friendId: friendId}
            });
        }

        private async getIsomerism(): Promise<any> {
            let result = await Http.get(this.api.meetIsomerism, {num: 15}, {token: this.user.token});
            if (result.code === 1) {
                for (let i in result.data) {
                    result.data[i].avatar = this.userFaceSafeHandle(result.data[i]);
                    this.tipsShow = this.dataCache.gameTip;
                    // data.push(Object.assign(result.data[i], {avatar: this.userFaceSafeHandle(result.data[i])}));
                }
                // console.log(data);
                this.encounterList.push(...result.data);
            }
        }

        private async getParameterItem(type: string): Promise<any> {
            try {
                let result = await Http.get(this.api.getParameterItem, {type: type});
                if (result.code === 1) {
                    let parameterItem = this.parameterItem;
                    parameterItem[type] = result.data;
                    this.parameterItem = Object.assign(this.parameterItem, parameterItem);
                }
            } catch (e) {
                console.log(e);
            }
        }

        private matchJson(type: string, value: number): string {
            for (let i in this.parameterItem[type]) {
                if (this.parameterItem[type][i].id === value) {
                    return this.parameterItem[type][i].name;
                }
            }
            return "";
        }

        private getLoveCount(): void {
            Http.get(this.api.getTodayLoveNum, {}, {token: this.user.token}).then((res) => {
                if (res.code === 1) {
                    this.loveCount = res.data.count;
                }
            });
        }

        private toDownload() {
            this.navigateTo({
                name: "appDownload"
            });
        }
    }
</script>
<style lang="stylus" scoped>
    .view
        height calc(100vh - 47px - var(--safe-area-inset-bottom));
        padding-top var(--safe-area-inset-top)
        background $theme-background-gradient
        position relative;

    .view-background
        background url("/assets/home-background.png") repeat;
        position relative;

    .home-radar
        width 100%;
        height 100%
        position absolute;
        top 0;
        left 0;
        background #fff;
        z-index 150;
        padding 30px 0 10px 0;
        display flex;
        justify-content center;
        align-items center;
        flex-direction column;

        .home-radar-text
            padding 7vh 12px 4vh 12px;
            color $theme-common-color;
            font-size 17px;
            line-height 1.5;
            letter-spacing 1px;

    .encounter-card-wrap-no-app
        height calc(100vh - 47px - var(--safe-area-inset-bottom) - var(--safe-area-inset-top) - 15.625vw) !important;

    .encounter-card-wrap
        height calc(100vh - 47px - var(--safe-area-inset-bottom) - var(--safe-area-inset-top))
        position relative;
        overflow hidden;
        width 100vw;
        padding 15px

        .encounter-card-item-no-app
            height calc(100vh - 47px - var(--safe-area-inset-bottom) - var(--safe-area-inset-top) - 30px - 15.625vw) !important;

        .encounter-card-item, .photo-masker
            position absolute;
            top 15px;
            left 15px;
            width calc(100vw - 30px);
            height calc(100vh - 47px - var(--safe-area-inset-bottom) - var(--safe-area-inset-top) - 30px);
            background #fff;
            border-radius 15px;
            overflow hidden;

            .encounter-card-image-no-app
                height calc(100vh - 47px - var(--safe-area-inset-bottom) - var(--safe-area-inset-top) - 30px - 100px - 15.625vw) !important;

            .encounter-card-image
                width calc(100vw - 30px);
                height calc(100vh - 47px - var(--safe-area-inset-bottom) - var(--safe-area-inset-top) - 30px - 100px);
                position relative;
                overflow hidden;
                text-align center;
                background-repeat none;
                background-size cover;
                background-position center;

            .encounter-card-intro
                height 100px;
                padding 15px 20px;
                display flex;
                flex-direction row;
                justify-content space-between;

                .encounter-card-desc
                    display flex;
                    flex-direction column;
                    justify-content space-between;

                    .encounter-card-name
                        height 45px;
                        line-height 45px;
                        font-size 21px;

                        i.encounter-card-sign
                            padding 1px 7px;
                            margin-left 6px;
                            font-size 9px;
                            font-style normal;
                            background #3ca0e6;
                            color #fff;
                            border-radius 30px


                    .encounter-card-base
                        height 30px;
                        font-size 14px;
                        color #666;
                        display flex;
                        align-items center;

                        i
                            display inline-block;
                            width 12px;
                            height 14px;
                            position relative;

                            &::before
                                content '';
                                display block
                                width 1.5px;
                                height 10px;
                                background #888;
                                position absolute;
                                left 5.25px;
                                top 2px;

                .encounter-card-matching
                    display flex;
                    flex-direction column;
                    align-items center;
                    justify-content center;
                    width 55px;

                    .encounter-card-number
                        font-size 20px;
                        color #333333;

                        &::after
                            content '%';
                            font-size 13px;
                            padding-left 1px;

                    .encounter-card-text
                        font-size 13px;
                        color #7f7f7f
                        padding-top 3px;

    .face-fade-wrap
        width 100vw;
        height 100vw;
        position relative;

        .face-fade-item
            position absolute;
            width calc(100vw / 7);
            height calc(100vw / 7);
            background-position center;
            background-size 100%;
            border-radius 100%;
            transform scale(0);
            animation-name face-scale;
            animation-duration 3s;
            border 2px solid $theme-common-color;
            box-sizing border-box;

    .like-number
        height 28px;
        padding 0 7px 0 10px;
        border-bottom-left-radius 14px;
        border-top-left-radius 14px;
        background #fff;
        position absolute;
        display flex;
        right 0;
        top calc(var(--safe-area-inset-top) + 40px);
        align-items center;
        color $theme-common-color

        i.iconfont
            padding-right 4px;

        .count
            font-size 15px;
            padding-left 2px;

    .like-number-no-app
        top calc(var(--safe-area-inset-top) + 40px + 15.625vw) !important;

    $keyframe-name := face-scale
    @keyframes {$keyframe-name}
        0%
            transform scale(0)
        30%
            transform scale(.95)
        60%
            transform scale(.95)
        100%
            transform scale(0)

    .app-download
        width 100vw;
        height 15.625vw;

        img
            width 100vw;
            height 15.625vw;

    .photo-masker
        background-image: url("/assets/images/no-other-user-to-women.jpg") !important;
        background-size cover !important;
        background-position center !important;
        display flex;
        flex-direction column;
        color #fff;
        justify-content center;
        align-items center;

        .photo-masker-icon
            font-size 70px;

        .photo-masker-text
            font-size 16px;
            line-height 2;

        &.photo-masker-men
            background-image: url("/assets/images/no-other-user-to-men.jpg") !important;

    .game-tip
        background rgba(0, 0, 0, .5)
        position absolute;
        top 0;
        left 0
        width 100vw;
        height 100vh
        display flex;
        flex-direction column;
        justify-content center;
        align-items center;
        color #fff;

        .game-tip-first
            width 100vw;
            padding 20px 35px;
            display flex;
            justify-content space-between;

        .game-tip-first-item, .game-tip-second
            display flex;
            flex-direction column;
            justify-content center;
            align-items center;

            i.iconfont
                font-size 50px;

            .tip-text
                font-size 16px;
                padding-top 20px;

        .game-tip-second
            padding-top 20vh;

            .tip-text
                font-size 13px;

        .game-tip-close
            width 100px;
            height 30px;
            display flex;
            justify-content center;
            align-items center;
            position absolute;
            bottom 50px;
            left 50%;
            margin-left -50px;
            border-radius 30px;
            font-size 12px;
            border 1px solid #f0f0f2;


</style>

